<template>
  <div class="categories-container">
    <div class="page-header">
      <h2 class="page-title">分类管理</h2>
      <el-button type="primary" @click="handleAdd">新增分类</el-button>
    </div>
    
    <el-table
      :data="categories"
      style="width: 100%"
      border
      stripe
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="分类名称" />
      <el-table-column prop="productCount" label="商品数量" width="100" align="center" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            plain
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            plain
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑分类' : '新增分类'"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'

// 分类列表
const categories = ref([])
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const categoryFormRef = ref(null)

// 分类表单
const categoryForm = reactive({
  id: null,
  name: ''
})

// 表单验证规则
const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取分类列表
const fetchCategories = async () => {
  loading.value = true
  try {
    const response = await api.get('/categories')
    if (response.data && response.data.status === 'success') {
      categories.value = response.data.data
      
      // 获取每个分类的商品数量
      await fetchCategoryProductCounts()
    } else {
      ElMessage.error('获取分类列表失败: ' + (response.data?.message || '未知错误'))
      // 加载硬编码数据作为备份
      loadHardcodedCategories()
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
    // 加载硬编码数据作为备份
    loadHardcodedCategories()
  } finally {
    loading.value = false
  }
}

// 获取每个分类的商品数量
const fetchCategoryProductCounts = async () => {
  try {
    const response = await api.get('/products')
    if (response.data && response.data.status === 'success') {
      const products = response.data.data
      
      // 统计每个分类的商品数量
      const counts = {}
      products.forEach(product => {
        if (product.categoryId) {
          counts[product.categoryId] = (counts[product.categoryId] || 0) + 1
        }
      })
      
      // 更新分类列表
      categories.value = categories.value.map(category => ({
        ...category,
        productCount: counts[category.id] || 0
      }))
    }
  } catch (error) {
    console.error('获取商品数量统计失败:', error)
  }
}

// 加载硬编码的备份分类数据
const loadHardcodedCategories = () => {
  categories.value = [
    { id: 1, name: '国产啤酒', productCount: 2 },
    { id: 2, name: '进口啤酒', productCount: 2 },
    { id: 3, name: '精酿啤酒', productCount: 1 },
    { id: 4, name: '果味啤酒', productCount: 1 }
  ]
}

// 新增分类
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(categoryForm, row)
  dialogVisible.value = true
}

// 删除分类
const handleDelete = (row) => {
  // 检查分类是否有商品
  if (row.productCount > 0) {
    ElMessage.warning(`该分类下有${row.productCount}个商品，不能删除`)
    return
  }
  
  ElMessageBox.confirm(`确定要删除分类"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 显示加载中，避免用户重复点击
      loading.value = true
      
      // 调用API删除分类
      const response = await api.delete(`/categories/${row.id}`)
      
      // 判断响应状态
      if (response.data && response.data.status === 'success') {
        ElMessage({
          message: '删除成功',
          type: 'success',
          showClose: true
        })
        // 重新获取分类列表
        fetchCategories()
      } else {
        ElMessage({
          message: '删除失败: ' + (response.data?.message || '未知错误'),
          type: 'error',
          showClose: true
        })
      }
    } catch (error) {
      console.error('删除分类失败:', error)
      ElMessage({
        message: '删除分类失败',
        type: 'error',
        showClose: true
      })
    } finally {
      loading.value = false
    }
  }).catch(() => {
    // 用户取消操作，不做任何处理
  })
}

// 重置表单
const resetForm = () => {
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields()
  }
  
  Object.assign(categoryForm, {
    id: null,
    name: ''
  })
}

// 提交表单
const submitForm = async () => {
  if (!categoryFormRef.value) return
  
  categoryFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      try {
        // 构造保存的分类数据
        const categoryData = { ...categoryForm }
        
        let response
        
        if (isEdit.value) {
          // 编辑分类 - 调用API
          response = await api.put(`/categories/${categoryData.id}`, categoryData)
        } else {
          // 新增分类 - 调用API
          delete categoryData.id
          response = await api.post('/categories', categoryData)
        }
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success(isEdit.value ? '分类编辑成功' : '分类添加成功')
          dialogVisible.value = false
          // 重新获取分类列表
          fetchCategories()
        } else {
          ElMessage.error((isEdit.value ? '编辑' : '添加') + '分类失败: ' + (response.data?.message || '未知错误'))
        }
      } catch (error) {
        console.error(isEdit.value ? '编辑分类失败:' : '添加分类失败:', error)
        ElMessage.error(isEdit.value ? '编辑分类失败' : '添加分类失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchCategories()
})
</script>

<style scoped>
.categories-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  margin: 0;
}
</style> 